import os
import requests
import re
import time
from sys import stdout

"服务端功能模块，从网站上下载文件，并保存"

# 模块具体功能
def ModuleOne(url,savepath):
    '''-------功能模块1------'''
    headers = {'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36'}

    # 1. 通过截取url，得到文件名
    filenames = re.split(r'/',url)[-1]
    if len(filenames) > 20:
        filenames = filenames[-20:]
    else:
        filenames = filenames

    # 2. 判断文件夹是否存在，如果不存在，则创建

    if not os.path.exists(savepath):
        os.mkdir(savepath)
    
    # 3. 下载文件并保存，显示下载进度
    response = requests.get(url,stream=True, headers=headers)
    if response.status_code == 200:
        length = response.headers['Content-Length']
        print('文件大小:%sM'%(int(length)/1024/1024))
        with open(savepath + filenames,'wb') as file:
            chunk_size=1024*1024*2
            times = int(length) // chunk_size
            show = 1 / times
            show2 = 1 / times
            start = 1
            for chunk in response.iter_content(chunk_size):
                file.write(chunk)
                if start <= times:
                    stdout.write(f"下载进度: {show:.2%}\r")
                    start = start + 1
                    show += show2
                else:
                    stdout.write("下载进度: 100%")
    else:
        print('有可能是网页不可达,请手动下载试试')
        
#ModuleOne()